import axios from '@/libs/api.request'
import { Message } from 'iview'
let httpUtil = {

}

// 异步post接口
// 参数url，data，successCallback，errorCallback
httpUtil.asyncPost = (url, data, successCallback, errorCallback) => {
  httpUtil.sendAjax('post', url, data, successCallback, errorCallback)
}

// 异步delete接口
// 参数url，data，successCallback，errorCallback
httpUtil.asyncDelete = (url, data, successCallback, errorCallback) => {
  httpUtil.sendAjax('delete', url, data, successCallback, errorCallback)
}

// 异步get接口
// 参数url，data，successCallback，errorCallback
httpUtil.asyncGet = (url, data, successCallback, errorCallback) => {
  httpUtil.sendAjax('get', url, data, successCallback, errorCallback)
}

httpUtil.loadImage = (url, data, successCallback) => {
  axios.request({
    method: 'post',
    url: url,
    data: data,
    responseType: 'blob'
  }).then((res) => {
    let reader = new FileReader()
    reader.onload = (e) => {
      successCallback(e.target.result)
    }
    reader.readAsDataURL(res)
  })
}

httpUtil.sendAjax = (method, url, data, successCallback, errorCallback) => {
  axios.request({
    method: method,
    url: url,
    data: data
  }).then(response => {
    successCallback(response)
  }).catch(function (response) {
    if (response.msg) Message.error(response.msg)
    if (errorCallback) {
      errorCallback(response)
    }
  })
}

// 分页查询
httpUtil.pageSearch = ({url = undefined, pageData = undefined, params = undefined, method = 'post', success = () => {}, error = () => {}}) => {
  /**
     * 如果 params 不为空， 则是重新查询， 否则是页切换操作
     */
  if (!params) {
    params = pageData._params
  }
  let _params = JSON.parse(JSON.stringify(params))
  // 缓存
  pageData._params = _params
  _params.current = pageData.current
  _params.size = pageData.size
  httpUtil.sendAjax(method, url, _params, (response) => {
    pageData.total = response.data.total
    success(response)
  }, error)
}
export default httpUtil
